﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GBT.Tool.Core;
using GBT.Tool.Core.ToolHelps;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NLog;

namespace WebAPI_QiSiMealSystem.Controllers
{
    [Route("gbt/[controller]")]
    [ApiController]
    public class FileManageController : ControllerBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        Tools tools = new Tools();
        WXOCRAPI wxocrapi = new WXOCRAPI();

        // GET: gbt/FileManage
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: gbt/FileManage/download/fileName
        [HttpGet("download/{fileName}")]
        public async Task<IActionResult> Get(string fileName)
        {
            try
            {
                var task = await Task.Run(() =>
                {
                    var path = Path.Combine(AppContext.BaseDirectory, "Photos", $@"{fileName}");
                    FileStream fs = new FileStream(path, FileMode.Open);
                    //return File(fs, "*/*", fileName);//下载图片
                    //return new FileStreamResult(fs, "image/png");//网络图片流
                    return new FileStreamResult(fs, "*/*");//网络图片流
                });
                return task;
            }
            catch
            {
                return NotFound();
            }
        }

        // GET: gbt/FileManage/barcode/companyId/content/uuid
        [HttpGet("barcode/{companyId}/{content}/{uuid}")]
        public async Task<IActionResult> GetBarCode(int companyId, string content, string uuid)
        {
            try
            {
                var task = await Task.Run(() =>
                {
                    var path = Path.Combine(AppContext.BaseDirectory, $@"Photos/{companyId.ToString()}", $@"{content}bar.png");

                    //创建条形码文件
                    tools.GenerateBarcode(content, companyId);

                    //读取二维码文件并输出
                    FileStream fs = new FileStream(path, FileMode.Open);
                    FileStreamResult fsr = new FileStreamResult(fs, "image/png");
                    return fsr;//二维码文件流
                });
                return task;
            }
            catch
            {
                return NotFound();
            }
        }

        // GET: gbt/FileManage/qrcode/companyId/content/uuid
        [HttpGet("qrcode/{companyId}/{content}/{uuid}")]
        public async Task<IActionResult> GetQRCode(int companyId, string content, string uuid)
        {
            try
            {
                var task = await Task.Run(() =>
                {
                    var path = Path.Combine(AppContext.BaseDirectory, $@"Photos/{companyId.ToString()}", $@"{content}.png");
                    
                    //创建二维码文件
                    tools.CreateQRCodeFile(companyId, content);

                    //读取二维码文件并输出
                    FileStream fs = new FileStream(path, FileMode.Open);
                    FileStreamResult fsr = new FileStreamResult(fs, "image/png");
                    return fsr;//二维码文件流
                });
                return task;
            }
            catch
            {
                return NotFound();
            }
        }

        // POST: gbt/FileManage/UploadPhotos
        [HttpPost("UploadPhotos")]
        public async Task<IActionResult> UploadPhotosAsync([FromForm(Name = "file")] IFormFileCollection files)
        {
            long size = 0;
            var fileName = "";
            var error = "";
            try
            {
                size = files.Sum(f => f.Length);
                var fileFolder = Path.Combine(AppContext.BaseDirectory, "Photos");

                if (!Directory.Exists(fileFolder))
                    Directory.CreateDirectory(fileFolder);

                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") +
                                       Path.GetExtension(file.FileName);
                        var filePath = Path.Combine(fileFolder, fileName);

                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message + Environment.NewLine + ex.StackTrace;
            }
            return Ok(new { count = files.Count, size, fileName, error });
        }

        // POST: gbt/FileManage/UploadPhoto
        [HttpPost("UploadPhoto")]
        public async Task<IActionResult> UploadPhotosAsync([FromForm(Name = "file")] IFormFile file)
        {
            var fileFolder = "";
            var fileName = "";
            var fileSize = 0L;
            var error = "";
            try
            {
                logger.Info("文件信息");
                logger.Info(file);
                logger.Info(file.ContentDisposition);
                logger.Info(file.FileName);
                logger.Info(file.Name);
                logger.Info(file.ContentType);

                fileFolder = Path.Combine(AppContext.BaseDirectory, "Photos");

                if (!Directory.Exists(fileFolder))
                    Directory.CreateDirectory(fileFolder);
                if (file != null)
                {
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(fileFolder, fileName);
                    fileSize = file.Length;

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                error = "Error:" + ex.Message + ex.StackTrace;
            }
            return Ok(new { fileName, fileSize, error });
        }

        // POST: gbt/FileManage/UploadPhotosOCR
        [HttpPost("UploadPhotosOCR")]
        public async Task<IActionResult> UploadPhotosOCR([FromForm(Name = "file")] IFormFile file)
        {
            OkObjectResult task = await Task.Run(() =>
            {
                var error = "";
                JObject joResult = new JObject();
                try
                {
                    logger.Info("文件信息");
                    logger.Info(file);
                    logger.Info(file.ContentDisposition);
                    logger.Info(file.FileName);
                    logger.Info(file.Name);
                    logger.Info(file.ContentType);

                    if (file != null)
                    {
                        joResult = wxocrapi.getOCR_BusinessLicense(file.OpenReadStream());
                    }
                    return Ok(new { root = joResult, error });
                }
                catch (Exception ex)
                {
                    error = "Error:" + ex.Message + Environment.NewLine + ex.StackTrace;
                    return Ok(new { root = joResult, error });
                }
            });
            return task;
        }

        // POST: gbt/FileManage
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT: gbt/FileManage/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: gbt/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
